package edu.whu.demo.security;

import edu.whu.demo.domain.Role;
import edu.whu.demo.domain.UserDto;
import edu.whu.demo.service.impl.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

// 定义一个名为DbUserDetailService的服务类，实现UserDetailsService接口
@Service
public class DbUserDetailService implements UserDetailsService {
    // 使用@Autowired注解注入UserService实例
    @Autowired
    UserService userService;

    // 重写loadUserByUsername方法，根据用户名加载用户详细信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 调用userService的getUser方法获取用户信息
        UserDto user = userService.getUser(username);
        // 如果用户不存在，抛出UsernameNotFoundException异常
        if (user == null) {
            throw new UsernameNotFoundException("User " + username + " is not found");
        }

        // 构建并返回UserDetails对象
        return User.builder()
                .username(username) // 设置用户名
                .password(user.getPassword()) // 设置密码
                .authorities(getAuthorities(user)) // 设置权限
                .build();
    }

    // 定义一个私有方法，根据用户的角色获取权限列表
    private static GrantedAuthority[] getAuthorities(UserDto user) {
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 遍历用户的角色列表
        for (Role role : user.getRoles()) {
            // 将角色的权限字符串按逗号分割成数组
            String[] authorityStrs = role.getAuthorities().split(",");
            // 遍历权限字符串数组，将每个权限添加到权限列表中
            for (String auth : authorityStrs) {
                authorities.add(new SimpleGrantedAuthority(auth));
            }
        }
        // 将权限列表转换为数组并返回
        return authorities.toArray(new GrantedAuthority[authorities.size()]);
    }
}